package cn.tnar.yunpark.xunlang;

import cn.tnar.yunpark.service.SensorEventDispatcher;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * author : CaineZhu
 * date   : 2017/12/22 ${time}
 * desc   : class desc
 */

@Component
public class XunLangUDPServer {

    Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    Bootstrap boss = null;
    EventLoopGroup group = null;
    @Value("${tnar.langxun.port}")
    private int port = 4701;
    @Autowired
    private SensorEventDispatcher dispatcher;



    public void server() {
        boss = new Bootstrap();
        group = new NioEventLoopGroup();
        try {
            boss.group(group)
                    .option(ChannelOption.SO_BROADCAST, true)//支持广播
                    .channel(NioDatagramChannel.class)
                    .handler(new XunLangMessageHandler(dispatcher));
            System.out.println("==========langxun udp server started==========");
            boss.bind(port).sync().channel().closeFuture().await();
        } catch (Exception e) {
            logger.error("netty init Exception:" + e.getLocalizedMessage());
        }
    }

    //关闭监听
    public void stopThread() {
        if (null != group && !group.isShutdown())
            group.shutdownGracefully();

        if (null != boss)
            boss = null;

    }
}
